<template>
  <div class="component-distribution-prod">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('coupon.commodityName') + ':'">
            <el-input
              v-model="searchForm.prodName"
              type="text"
              clearable
              :placeholder="$t('coupon.commodityName')"
            />
          </el-form-item>
          <el-form-item
            prop="state"
            :label="$t('product.status') + ':'"
          >
            <el-select
              v-model="searchForm.state"
              :placeholder="$t('product.status')"
              clearable
            >
              <el-option
                :label="$t('prodList.ShopkeeperOffShelf')"
                :value="0"
              />
              <el-option
                :label="$t('publics.metUpperShelf')"
                :value="1"
              />
              <el-option
                :label="$t('groups.offlineViolation')"
                :value="2"
              />
              <el-option
                :label="$t('product.pendingReview')"
                :value="3"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch('searchForm')"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <!-- 表格 -->
      <div class="table-con distribution-prod-table">
        <el-table
          ref="distributionProdListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
        >
          <!-- 商城名称 -->
          <el-table-column
            width="300"
            prop="shopName"
            :label="$t('prodList.shopName')"
          >
            <template #default="scope">
              <div class="table-cell-text">
                {{ scope.row.product.shopName }}
              </div>
            </template>
          </el-table-column>

          <!-- 商品信息 -->
          <el-table-column
            min-width="260"
            :label="$t('product.prodInfo')"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <prod-pic :pic="scope.row.product.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.product.prodName }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- 状态 -->
          <el-table-column
            prop="state"
            :label="$t('product.status')"
          >
            <template #default="scope">
              <div
                v-if="scope.row.state === 0"
                class="tag-text"
              >
                {{ $t("prodList.ShopkeeperOffShelf") }}
              </div>
              <div
                v-if="scope.row.state === 1"
                class="tag-text"
              >
                {{ $t("publics.metUpperShelf") }}
              </div>
              <div
                v-if="scope.row.state === 2"
                class="tag-text"
              >
                {{ $t("groups.offlineViolation") }}
              </div>
              <div
                v-if="scope.row.state === 3"
                class="tag-text"
              >
                {{ $t("product.pendingReview") }}
              </div>
            </template>
          </el-table-column>
          <!-- 奖励比例 -->
          <el-table-column
            min-width="100"
            prop="state"
            :label="$t('marketing.rewardRatio')"
          >
            <template #default="scope">
              <div
                v-if="scope.row.awardProportion === 0"
                class="tag-text"
              >
                {{ $t("marketing.proporteward") }}
              </div>
              <div
                v-if="scope.row.awardProportion === 1"
                class="tag-text"
              >
                {{ $t("marketing.rewardByFixedValue") }}
              </div>
            </template>
          </el-table-column>
          <!-- 间推奖励 -->
          <el-table-column
            prop="state"
            :label="$t('marketing.inviterReward')"
          >
            <template #default="scope">
              <div
                v-if="scope.row.parentAwardSet === 0"
                class="tag-text"
              >
                {{ $t("seckill.close") }}
              </div>
              <div
                v-if="scope.row.parentAwardSet === 1"
                class="tag-text"
              >
                {{ $t("seckill.open") }}
              </div>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="230"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('platform:distributionProd:info')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row)"
                >
                  {{ $t('prodList.lookOver') }}
                </div>
                <div
                  v-if="isAuth('platform:distributionProd:update') && scope.row.state<2"
                  class="default-btn text-btn"
                  @click="offlineDistributionProdHandle(scope.row)"
                >
                  {{ $t('product.violation') }}
                </div>
                <div
                  v-if="isAuth('platform:distributionProd:update') && scope.row.state > 1"
                  class="default-btn text-btn"
                  @click="distributionProdAuditHandle(scope.row.distributionProdId)"
                >
                  {{ scope.row.state === 2
                    ? $t("prodList.offShelfManage")
                    : $t("coupon.checkPending") }}
                </div>
                <div
                  v-if="isAuth('platform:distributionProd:delete')"
                  class="default-btn text-btn"
                  @click="deleteHandle(scope.row)"
                >
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 商品审核弹窗 -->
    <offline-audit
      v-if="distributionProdAuditVisible"
      ref="distributionProdAuditRef"
      select-url="/platform/distributionProd/getOfflineEventByDistProdId"
      update-url="/platform/distributionProd/auditDistributionProd"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './distribution-prod-add-or-update.vue'

onMounted(() => {
  getDataList(page)
})

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
/**
 * 新增 / 修改
 * @param data
 */
const onAddOrUpdate = (data) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(data)
  })
}

/**
 * 点击查询
 * @param newData
 */
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

/**
 * 刷新回调
 */
const refreshChange = () => {
  getDataList(page)
}

let tempSearchForm = null // 保存上次点击查询的请求条件
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = ref({
  prodName: ''
})
const dataList = ref([])
/**
 * 获取数据列表
 * @param pageParam
 * @param newData
 */
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm.value))
  }
  http({
    url: http.adornUrl('/platform/distributionProd/page'),
    method: 'get',
    params: http.adornParams(Object.assign({
      current: pageParam ? pageParam.currentPage : 1,
      size: pageParam ? pageParam.pageSize : 20
    }, tempSearchForm))
  })
    .then(({ data }) => {
      page.total = data.total
      page.pageSize = data.size
      page.currentPage = data.current
      dataList.value = data.records

      // 末尾页数据为空重新请求
      if (!dataList.value.length && page.currentPage > 1) {
        page.currentPage = 1
        getDataList()
      }
    })
}

/**
 * 下线活动
 * @param row
 */
const offlineDistributionProdHandle = (row) => {
  // '确定对活动需要修改[' + row.couponName + ']进行下线操作？如是，请填写下线理由'
  let tips = $t('groups.removeActivityNameTips')
  tips = tips.replace('ACTIVITYNAME', row.product.prodName)
  ElMessageBox.prompt(tips, $t('text.tips'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    inputPattern: /\s\S+|S+\s|\S/, // 不能全为空格 空字符串
    inputErrorMessage: $t('seckill.offlineReasonTip'),
    inputValidator: (value) => {
      if (value.length > 100) {
        return $t('seckill.offlineReasonTip1')
      }
    }
  }).then((obj) => {
    http({
      url: http.adornUrl('/platform/distributionProd/offline'),
      method: 'post',
      data: http.adornData({
        handleId: row.distributionProdId,
        offlineReason: obj.value || null
      })
    })
      .then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            getDataList(page)
          }
        })
      })
  })
}
/**
 * 删除商品
 * @param row
 */
const deleteHandle = (row) => {
  const ids = row.distributionProdId ? [row.distributionProdId] : this.dataListSelections.map(item => {
    return item.distributionProdId
  })
  ElMessageBox.confirm($t('remindPop.makeSure') + ' ' + `[${row.distributionProdId ? $t('remindPop.delete') : $t('remindPop.batchDeletion')}]` + ' ' + $t('remindPop.operation') + '?', $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl('/platform/distributionProd'),
        method: 'delete',
        data: http.adornData(ids, false)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            getDataList(page)
          }
        })
      })
    })
}

const distributionProdAuditVisible = ref(false)
const distributionProdAuditRef = ref(null)
/**
 * 弹窗处理
 * @param id
 */
const distributionProdAuditHandle = (id) => {
  distributionProdAuditVisible.value = true
  nextTick(() => {
    distributionProdAuditRef.value?.init(id)
  })
}

const searchFormRef = ref(null)
/**
 * 重置表单
 */
const onResetSearch = () => {
  searchFormRef.value?.resetFields()
  searchForm.value = {}
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}

const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}
</script>
